package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.util.StrUtil;
import cn.lili.modules.order.order.entity.dos.FirstBuyRecord;
import cn.lili.modules.order.order.mapper.FirstBuyRecordMapper;
import cn.lili.modules.order.order.service.FirstBuyRecordService;
import cn.lili.modules.share.client.ShareRegisterClient;
import com.alibaba.fastjson.JSONObject;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojos.OpenAppUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 首次购买记录 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-04-02
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FirstBuyRecordServiceImpl extends ServiceImpl<FirstBuyRecordMapper, FirstBuyRecord> implements FirstBuyRecordService {

    private final ShareRegisterClient shareRegisterClient;
    private final UserApi userApi;
    /**
     * 检测是否存在更新分享注册里的首次购买标识
     *
     * @param openid
     * @return
     */
    @Override
    public int judeUpdateFirstBuyRecord(String userId, String openid, String mobile) {
        //查询openid对应的分享openid
        OpenAppUser openAppUser = userApi.getShareOpenIdByOpenId(openid);
        log.info("#payOrder# #judeUpdateFirstBuyRecord# 查询openid对应的分享openid, openid:{},结果:{}", openid, openAppUser != null ? JSONObject.toJSONString(openAppUser) : null);
        if (openAppUser == null || StrUtil.isEmpty(openAppUser.getOpenId())) {
            return 0;
        }
        openid = openAppUser.getOpenId();
        LambdaQueryWrapper<FirstBuyRecord> query = new LambdaQueryWrapper<>();
        query.eq(true, FirstBuyRecord::getOpenid, openid);
        //判断是否已经存在
        long existCount = baseMapper.selectCount(query);
        log.info("#payOrder# #judeUpdateFirstBuyRecord# 检测是否存在更新分享注册里的首次购买标识,查询本地是否已存在标识,参数:{},结果:{}", openid, existCount);
        if ( existCount== 0) {
            //更改购买标识
            int result = shareRegisterClient.updateAppUserIsTureByOpenId(openid);
            log.info("#payOrder# #judeUpdateFirstBuyRecord# 检测是否存在更新分享注册里的首次购买标识,shareRegisterClient.updateAppUserIsTureByOpenId,参数:{}, 执行结果:{}}", openid, result);
            if (result > 0) {
                FirstBuyRecord firstBuyRecord = new FirstBuyRecord();
                firstBuyRecord.setOpenid(openid);
                firstBuyRecord.setUserId(userId);
                firstBuyRecord.setMobile(mobile);
                //记录本库标识
                baseMapper.insert(firstBuyRecord);
            }
        }
        return 1;
    }
}
